#include "Socket.hpp"
#include <poll.h>

class PollServer
{
    const static int defaultfd = -1;
    const static int size = 4096;
public:
    PollServer(int port)
        :_listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildTcpListenSocket(port);
        
        for(int i = 0; i < size; i++)
        {
            _fds[i].fd = defaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }

        _fds[0].fd = _listensock->Fd();
        _fds[0].events = POLLIN; // 等待读事件
    }

    void Start()
    {
        _isrunning = true;

        int timeout = 1000;
        while(_isrunning)
        {
            //等待
            int n = poll(_fds, size, timeout);
            switch(n)
            {
                case 0:
                    LOG(LogLevel::INFO) << "time out";
                break;
                case -1:
                    LOG(LogLevel::ERROR) << "error";
                break;
                default: // 等到了，做处理
                    HanderEvent();
                    LOG(LogLevel::DEBUG) << "poll success";
                break;
            }
        }
        _isrunning = false;
    }

    //事件配发器
    void HanderEvent()
    {
        //此时等待就绪，两种情况：监听就绪/sockfd就绪
        //判断就绪的文件是哪一种，然后分类讨论
        for(int i = 0; i < size; i++)
        {
            if(_fds[i].fd != defaultfd && (_fds[i].revents & POLLIN))
            {
                //判断该描述符是监听还是socket
                if(_fds[i].fd == _listensock->Fd())
                {
                    Accepter();
                }
                else
                {
                    Recver(i);
                }
            }
        }
    }

    //链接管理器
    void Accepter()
    {
        //获取客户端IP和端口
        InetAddr client;
        int sockfd = _listensock->Accept(&client);
        if(sockfd != -1) // 将新的文件描述符加入描述符集
        {
            for(int i = 0; i < size; i++)
            {
                if(_fds[i].fd != defaultfd)
                {
                    _fds[i].fd = sockfd;
                    _fds[i].events = POLLIN;
                    break;
                }
                if(i == size - 1) // 超出最大限制
                {
                    LOG(LogLevel::WARING) << "fd full";
                    close(sockfd);
                }
            }
        }
    }

    //IO处理器
    void Recver(int pos)
    {
        char buff[1024];
        int n = recv(_fds[pos].fd, buff, sizeof(buff) - 1, 0);
        if(n > 0) // 读到了
        {
            buff[n] = '\0';
            LOG(LogLevel::INFO) << "client say: " << buff;
        }
        else if(n == 0) // 客户端退出
        {
            LOG(LogLevel::INFO) << "客户端退出";

            //关闭文件
            close(_fds[pos].fd);

            //描述符集中去除对应sockfd
            _fds[pos].fd = defaultfd;
        }
        else // 读取错误
        {
            LOG(LogLevel::ERROR) << "读取错误";
            
            //关闭文件
            close(_fds[pos].fd);

            //描述符集中去除对应sockfd
            _fds[pos].fd = defaultfd;
        }
    }

    void Stop()
    {
        _isrunning = false;
    }
private:
    std::unique_ptr<Socket> _listensock;
    bool _isrunning = false;
    
    pollfd _fds[size];
};